package github.saw96x.common.factory;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 单例模式工厂
 *
 * @author Saw96x
 * @date 2022/3/18 8:44
 */
public final class SingletonFactory {
  private static final Map<String, Object> OBJECT_MAP = new ConcurrentHashMap<>();

  private SingletonFactory() {
  }

  public static <T> T getInstance(Class<T> c) {
    if (c == null) {
      throw new IllegalArgumentException();
    }
    String key = c.toString();
    if (OBJECT_MAP.containsKey(key)) {
      return c.cast(OBJECT_MAP.get(key));
    } else {
      return c.cast(OBJECT_MAP.computeIfAbsent(key, k -> {
        try {
          return c.getDeclaredConstructor().newInstance();
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
          throw new RuntimeException(e.getMessage(), e);
        }
      }));
    }
  }
}
